package com.cw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.api.ResultObject;
import com.cw.dto.BaseDictListDto;
import com.cw.dto.BaseDictTree;
import com.cw.entity.BaseDict;
import com.cw.mapper.BaseDictMapper;
import com.cw.mapper2.BaseDict2Mapper;
import com.cw.service.IBaseDictService;
import com.cw.util.UUIDUtil;
import com.cw.vo.BaseDictVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author ly
 * @since 2021-04-26
 */
@Service
public class BaseDictServiceImpl extends ServiceImpl<BaseDictMapper, BaseDict> implements IBaseDictService {

    @Autowired
    private BaseDict2Mapper baseDict2Mapper;

    @Override
    public List<BaseDictTree> getAllBaseDicts() {
        return baseMapper.getAllBaseDicts();
    }

    @Override
    public List<BaseDict> getBaseDictsByKindList(List<String> list) {
        return null;
    }

    @Override
    public List<BaseDictTree> getProPlanBaseDict() {
        return baseMapper.getProPlanBaseDict();
    }

    @Override
    public ResultObject getBaseDictById(String id) {
        //获得父节点找到所有子节点信息
        final List<BaseDict> parent = baseMapper.getBaseDictByparentId(id);
        if (!CollectionUtils.isEmpty(parent)) {
            for (final BaseDict baseDict : parent) {
                getChildrenByParentId(baseDict);
            }
        }
        return ResultObject.successReturn(parent);
    }

    /**
     * 获取字典表的对象以及他的子级
     *
     * @param id 主键
     * @return java.util.List<com.cw.entity.BaseDict>
     * @author ly
     * @date 2021/4/30 10:46
     */
    @Override
    public List<BaseDict> getBaseDictByIdResultList(String id) {
        final List<BaseDict> parent = baseMapper.getBaseDictByparentId(id);
        if (!CollectionUtils.isEmpty(parent)) {
            for (final BaseDict baseDict : parent) {
                getChildrenByParentId(baseDict);
            }
        }
        return parent;
    }

    /**
     * 获得父节点找到所有子节点信息
     * @param
     */
    private void getChildrenByParentId(BaseDict baseDict) {
        final String id = baseDict.getId();
        LambdaQueryWrapper<BaseDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BaseDict::getParentId, id)
                          .eq(BaseDict::getDeleteFlag, "0")
                          .eq(BaseDict::getEnable, "0");

        final List<BaseDict> parent = list(lambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(parent)) {
            baseDict.setChildren(parent);
            for (final BaseDict baseDict1 : parent) {
                getChildrenByParentId(baseDict1);
            }
        }

    }


    @Override
    public ResultObject deleteBaseDictVoByIds(List<String> id) {
        for (String s : id) {
            removeById(s);
        }

        return ResultObject.successReturn("操作成功!");
    }

    @Override
    public ResultObject addBaseDictVo(BaseDict baseDict) {
        baseDict.setId(UUIDUtil.uuid());
        baseDict.setCreateTime(LocalDateTime.now());
        //如果前端没传父级id，默认赋值为0
        if (StringUtil.isEmpty(baseDict.getParentId())) {
            baseDict.setParentId("0");
        }
        return ResultObject.successReturn(save(baseDict));
    }

    @Override
    public ResultObject updateBaseDictVo(BaseDict baseDict) {
        return ResultObject.successReturn(updateById(baseDict));
    }

    @Override
    public List<BaseDictVo> getParentBaseDict(String id) {
        return baseMapper.getParentBaseDict(id);
    }

    @Override
    public List<BaseDictTree> baseDictTrees(String parentId, List<BaseDictTree> allBaseDicts) {
        if (CollectionUtils.isEmpty(allBaseDicts)) {
            return null;
        }
        List<BaseDictTree> childBaseDict = new ArrayList<>();
        for (BaseDictTree baseDictTree : allBaseDicts) {
            if (baseDictTree.getParentId().equals(parentId)) {
                childBaseDict.add(baseDictTree);
            }

        }

        //判断是否有子菜单
        if (childBaseDict.size() == 0) {
            return null;
        }

        for (BaseDictTree baseDictTree : childBaseDict) {
            baseDictTree.setChildNodes(baseDictTrees(baseDictTree.getId(), allBaseDicts));
        }
        return childBaseDict;
    }

    /**
     * 字典表列表
     *
     * @param baseDictListDto 查询条件
     * @return java.util.List<com.kszs.pojo.BaseDictTree>
     * @author ly
     * @date 2020/10/13 14:20
     */
    @Override
    public PageInfo<BaseDictTree> getAllBaseDicts(BaseDictListDto baseDictListDto) {
        if (StringUtil.isEmpty(baseDictListDto.getId())) {
            baseDictListDto.setId("0");
        }
        PageHelper.startPage(baseDictListDto.getPageNum(), baseDictListDto.getPageSize());
        List<BaseDictTree> baseDictTrees = baseMapper.getAllBaseDictsList(baseDictListDto);
        return new PageInfo<>(baseDictTrees);
    }

    @Override
    public boolean deleteBaseDictBatch(List<String> ids) {
        List<String> childrens = new ArrayList<>();
        for (String id : ids) {
            deleteBaseDictChildren(id,childrens);
            removeById(id);
        }

        for (String children : childrens) {
            removeById(children);
        }
        return false;
    }

    /**
     * 批量编辑状态
     * @param list   集合
     * @param status 状态0启动 1关闭
     * @return boolean
     * @author ly
     * @date 2020/10/13 14:58
     */
    @Override
    public boolean updateEnableStatusBatch(List<String> list, String status) {
        for (String s : list) {
            BaseDict baseDict = new BaseDict();
            baseDict.setId(s);
            baseDict.setEnable(status);
            updateById(baseDict);
        }
        return false;
    }

    /**
     * 获取字典表单个详情
     * @param id 主键
     * @return com.kszs.entity.BaseDict
     * @author ly
     * @date 2020/10/15 11:35
     */
    @Override
    public BaseDict getBaseDictByIdDetail(String id) {
        return getById(id);
    }

    /**
     * 递归删除字典表子级
     * @param id 主键
     * @param childrens 子级集合
     * @author ly
     * @date 2020/10/13 14:55
     */
    private void deleteBaseDictChildren(String id, List<String> childrens) {
        QueryWrapper<BaseDict> entityWrapper = new QueryWrapper<>();
        entityWrapper.eq("PARENT_ID", id);

        List<BaseDict> baseDicts = list(entityWrapper);

        if (!CollectionUtils.isEmpty(baseDicts)) {
            childrens.addAll(baseDicts.stream().map(BaseDict::getId).collect(Collectors.toList()));
            for (BaseDict baseDict : baseDicts) {
                deleteBaseDictChildren(baseDict.getId(), childrens);
            }
        }

    }

    /**
     *数据项列表查询功能
     * @param id 主键
     * @param name 菜单名字
     * @return com.cw.common.api.ResultObject
     */
    @Override
    public ResultObject getBaseDictByIdAndName(String id, String name,String status,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        //获得父节点找到所有子节点信息
        final List<BaseDict> parent = baseMapper.getBaseDictByIdAndName(id,name,status);
//        if (!CollectionUtils.isEmpty(parent)) {
//            for (final BaseDict baseDict : parent) {
//                getChildrenByParentId(baseDict);
//            }
//        }
        return ResultObject.successReturn(new PageInfo<>(parent));
    }

    /**
     * 获取手工录入的下拉框
     * @return java.util.List<com.cw.entity.BaseDict>
     * @author ly
     * @date 2021/5/13 17:48
     */
    @Override
    public Map<String,List<BaseDict>> getBaseDictByIiPrepayin() {
        //入院情况
        List<BaseDict> insource = baseDict2Mapper.getInsource();
        //联系人关系
        List<BaseDict> relative = baseDict2Mapper.getRelative();
        //结算类型
        List<BaseDict> paykinds = baseDict2Mapper.getPaykinds();

        Map<String, List<BaseDict>> map = new HashMap<>(2);
        map.put("insource",insource);
        map.put("relative",relative);
        map.put("paykinds",paykinds);
        return map;
    }
}
